<?php
/***
* @version $Id: admin_layout.php 336 2007-01-23 08:12:56Z flexiondotorg $
* @copyright (c) 2006 - 2007 Flexion.Org
*            (c) 2004 - 2005 Project Minerva
*            (c) 2001 - 2006 phpBB Group
* @license   http://opensource.org/licenses/gpl-license.php GNU Public License
***/

define('IN_R3BORN', true);

if( !empty($setmodules) )
{
    $module['Modules']['Layout_manage'] = basename(__FILE__);
    return;
}

//
// Load default header
//
$root_path = './../';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
require('./pagestart.' . $phpEx);
include_once($root_path. 'includes/functions_selects.' . $phpEx);

$mode = get_var('mode', '');

if ($mode == '')
{
    //
    // These could be entered via a form button
    //
    if( isset($_POST['add']) )
    {
        $mode = 'add';
    }
    else if( isset($_POST['save']) )
    {
        $mode = 'save';
    }
    else
    {
        $mode = '';
    }
}

if(isset($_POST['cancel']))
{
    $mode = '';
}

$default_layout = $config['default_layout'];

if ( $mode != '' )
{
    if ( $mode == 'edit' || $mode == 'add')
    {
		$layout_id = get_var('layout_id', 0);

		$layout_groups = array();
		$layout_row = array();
		$s_hidden_fields = '';

       	$template->set_filenames(array(
            'body' => 'layout_edit_body.tpl')
        );

        if ($mode == 'edit')
        {
			if( $layout_id)
			{
				$sql = "SELECT *
                  		FROM " . LAYOUT_TABLE . "
                  		WHERE layout_id = $layout_id";
				if(!$result = $db->sql_query($sql))
           		{
					message_die(GENERAL_ERROR, 'Could not query layout table', 'Error', __LINE__, __FILE__, $sql);
				}

				$layout_row = $db->sql_fetchrow($result);
           		$db->sql_freeresult($result);

				$layout_groups = explode(',', $layout_row['groups']);

           		$s_hidden_fields .= '<input type="hidden" name="layout_id" value="' . $layout_id . '" />';
			}
  			else
   			{
				message_die(GENERAL_MESSAGE, $lang['No_layout_selected']);
			}
		}

		$viewlist = user_auth_select($layout_row['layout_view'], 'layout_view');
		$grouplist 	= group_auth_select($layout_groups);

		// Populate the layout selection list
		// If we are editting a layout, just display the layout name.
		if ($mode == 'edit')
		{
			foreach ($mvLayouts as $url => $mvLayout)
			{
				if ($url == $layout_row['layout_url'])
				{
					$display_name = $name_select = $mvLayout['name'];
					break;
				}
			}

			//$s_hidden_fields .= '<input type="hidden" name="layout_name" value="' . $layout_row['layout_name'] . '" />';
			$s_hidden_fields .= '<input type="hidden" name="layout_url" value="' . $layout_row['layout_url'] . '" />';
		}
		else
		{
			// Build a list of layouts which have not already been created.
			$sql = 'SELECT * FROM ' . LAYOUT_TABLE;
			if(!$result = $db->sql_query($sql))
			{
				message_die(GENERAL_ERROR, 'Could not query layout table', 'Error', __LINE__, __FILE__, $sql);
			}

			while ( $row = $db->sql_fetchrow($result) )
			{
				if ($layout_row['layout_url'] != $row['layout_url'])
				{
					$defined_layouts[] = $row['layout_url'];
				}
			}

			$db->sql_freeresult($result);

			$name_select = '<select name="layout_url" class="post">';

			$found_undefined_layouts = false;

			foreach ($mvLayouts as $url => $mvLayout)
			{
				//if ($url == $layout_rows[$i]['layout_url'])
				if (!in_array($url, $defined_layouts))
				{
					$found_undefined_layouts = true;
					$name_select .= '<option value="' . $url .'" ';
					$display_name = $mvLayout['name'];
					$name_select .= '>' . $display_name;
				}
			}


			$name_select .= '</select>';

			// If there are no layouts remaining that can be added don't both displaying the "add layout" form page
			// Display a message instead.
			if (!$found_undefined_layouts)
        	{
	        	$message = $lang['All_layouts_added'];
	        	$message .= "<br /><br />" . sprintf($lang['Click_return_layoutadmin'], "<a href=\"" . append_sid("admin_layout.$phpEx") . "\">", "</a>") . "<br /><br />" . sprintf($lang['Click_return_admin_index'], "<a href=\"" . append_sid("index.$phpEx?pane=right") . "\">", "</a>");
        		message_die(GENERAL_MESSAGE, $message);
    		}
		}

        $template->assign_vars(array(
            'L_LAYOUT_TITLE' => $lang['Layout_Title'],
            'L_LAYOUT_TEXT' => $lang['Layout_Explain'],
            'L_LAYOUT_NAME' => $lang['Layout_Name'],
			'L_LAYOUT_URL' => $lang['Layout_URL'],
            'L_LAYOUT_VIEW' => $lang['User_Level'],
            'L_LAYOUT_GROUPS' => $lang['Usergroups'],
			'DISPLAY_NAME' => ($mode == 'edit') ? $display_name : '',
            'NAME_SELECT' => $name_select,
			'URL' => $layout_row['layout_url'],
            'VIEW' => $viewlist,
            'GROUPS' => $grouplist,
            'L_LAYOUT_ACTION' => ($mode == 'edit') ? $lang['Layout_Edit'] : $lang['Layout_Add'],
            'L_SUBMIT' => $lang['Submit'],
            'S_LAYOUT_ACTION' => append_sid('admin_layout.' . $phpEx),
            'S_HIDDEN_FIELDS' => $s_hidden_fields)
        );

		if ($mode == 'edit')
		{
			$template->assign_block_vars('switch_layout_edit', array());
		}

        $template->pparse('body');

        page_footer_admin();
	}
else if( $mode == 'save' )
    {
		$layout_id = get_var('layout_id', 0);
		$layout_url = get_var('layout_url', '');
		$layout_view = get_var('layout_view', 0);

		// Validate input
		if ($layout_url == '')
        {
            message_die(GENERAL_MESSAGE, $lang['Layout_details_incomplete']);
        }

        $layout_groups = prepare_group_list();

        $first_group = true;
        for ($i = 1; $i <= $row['max_group_id']; $i++)
        {
            if (isset($_POST['group' . strval($i)]))
            {
                if ($first_group)
                {
	                $layout_groups .= strval($i);
                    $first_group = false;
                }
				else
                {
                    $layout_groups .= ',' . strval($i);
                }
            }
        }

		//Determine the module id associated with this layout
		$module_id = 0;

		foreach ($mvLayouts as $url => $mvLayout)
		{
			if ($url == $layout_url)
			{
				$module_id = $mvLayout['module_id'];
				break;
			}
		}

        if ( $layout_id )
        {
            $sql = "UPDATE " . LAYOUT_TABLE . " SET
            	layout_url = '" . str_replace("\'", "''", $layout_url) . "',
                layout_view = '" . $layout_view . "',
                groups = '" . $layout_groups . "',
				module_id = '" . $module_id . "'
                WHERE layout_id = $layout_id";
            if (!$result = $db->sql_query($sql))
            {
                message_die(GENERAL_ERROR, "Could not insert data into layout table", $lang['Error'], __LINE__, __FILE__, $sql);
            }

            $message = $lang['Layout_updated'];
        }
        else
        {
			$sql = "INSERT INTO " . LAYOUT_TABLE . " (layout_url, layout_view, groups, module_id)
                VALUES ('" . str_replace("\'", "''", $layout_url) . "', '" . $layout_view . "', '" . $layout_groups . "', '" . $module_id . "')";
            if (!$result = $db->sql_query($sql))
            {
                message_die(GENERAL_ERROR, "Could not insert data into layout table", $lang['Error'], __LINE__, __FILE__, $sql);
            }
            $message = $lang['Layout_added'];
        }

        $message .= "<br /><br />" . sprintf($lang['Click_return_layoutadmin'], "<a href=\"" . append_sid("admin_layout.$phpEx") . "\">", "</a>") . "<br /><br />" . sprintf($lang['Click_return_admin_index'], "<a href=\"" . append_sid("index.$phpEx?pane=right") . "\">", "</a>");
        message_die(GENERAL_MESSAGE, $message);
    }
    else if ( $mode == 'delete' )
    {
		$layout_id = get_var('layout_id',0);

        if (!isset($_POST['confirm']))
        {
            $hidden_fields = '<input type="hidden" name="mode" value="'.$mode.'" /><input type="hidden" name="layout_id" value="'.$layout_id.'" />';

            //
            // Set template files
            //
            $template->set_filenames(array(
                "confirm" => "confirm_body.tpl")
            );

            $template->assign_vars(array(
                "MESSAGE_TITLE" => $lang['Confirm'],
                "MESSAGE_TEXT" => $lang['Confirm_delete_item'],

                "L_YES" => $lang['Yes'],
                "L_NO" => $lang['No'],

                "S_CONFIRM_ACTION" => append_sid('admin_layout.' . $phpEx),
                "S_HIDDEN_FIELDS" => $hidden_fields)
            );

            $template->pparse('confirm');
            exit();
        }
		else
        {
            if ( $layout_id )
            {
                $sql = "DELETE FROM " . LAYOUT_TABLE . "
                    WHERE layout_id = $layout_id";

                if (!$result = $db->sql_query($sql))
                {
                    message_die(GENERAL_ERROR, "Could not remove data from layout table", $lang['Error'], __LINE__, __FILE__, $sql);
                }

                $sql = "DELETE FROM " . BLOCKS_TABLE . "
                    WHERE layout_id = $layout_id";

                if (!$result = $db->sql_query($sql))
                {
                    message_die(GENERAL_ERROR, "Could not remove data from blocks table", $lang['Error'], __LINE__, __FILE__, $sql);
                }

                $message = $lang['Layout_removed'] . "<br /><br />" . sprintf($lang['Click_return_layoutadmin'], "<a href=\"" . append_sid("admin_layout.$phpEx") . "\">", "</a>") . "<br /><br />" . sprintf($lang['Click_return_admin_index'], "<a href=\"" . append_sid("index.$phpEx?pane=right") . "\">", "</a>");

                message_die(GENERAL_MESSAGE, $message);
            }
            else
            {
                message_die(GENERAL_MESSAGE, $lang['No_layout_selected']);
            }
        }
    }
}
else
{
	$default = get_var('default',0);

	if ( $default != 0)
    {
        $sql = "UPDATE " . CONFIG_TABLE . " SET config_value = '" . $default . "' WHERE config_name = 'default_layout'";

        if ( !$result = $db->sql_query($sql) )
        {
            message_die(GENERAL_ERROR, 'Could not update config table', $lang['Error'], __LINE__, __FILE__, $sql);
        }

        $default_layout = $default;
    }

    $template->set_filenames(array(
        'body' => 'layout_list_body.tpl')
    );

    $sql = "SELECT *
        FROM " . LAYOUT_TABLE . "
        ORDER BY module_id";
    if( !$result = $db->sql_query($sql) )
    {
        message_die(GENERAL_ERROR, 'Could not query layout table', $lang['Error'], __LINE__, __FILE__, $sql);
    }

    $layout_rows = $db->sql_fetchrowset($result);

    $template->assign_vars(array(
        'L_LAYOUT_TITLE' => $lang['Layout_Title'],
        'L_LAYOUT_TEXT' => $lang['Layout_Explain'],
        'L_LAYOUT_NAME' => $lang['Layout_Name'],
		'L_LAYOUT_URL' => $lang['Layout_URL'],
        'L_LAYOUT_ID' => $lang['Layout_ID'],
        'L_LAYOUT_VIEW' => $lang['User_Level'],
        'L_LAYOUT_GROUPS' => $lang['Usergroups'],
        'L_LAYOUT_EDIT' => $lang['Edit'],
        'L_LAYOUT_ADD' => $lang['Layout_Add'],
        'L_LAYOUT_ACTION' => $lang['Action'],
        'S_LAYOUT_ACTION' => append_sid('admin_layout.' . $phpEx),
        'S_HIDDEN_FIELDS' => '')
    );

    for ($i = 0; $i < count($layout_rows); $i++)
    {
        $layout_url = $layout_rows[$i]['layout_url'];

		foreach ($mvLayouts as $url => $mvLayout)
		{
			if ($url == $layout_url)
			{
				$layout_name = $mvLayout['name'];
				break;
			}
		}

        $layout_id = $layout_rows[$i]['layout_id'];

        $row_class = ( !($i % 2) ) ? 'row1' : 'row2';

        switch ($layout_rows[$i]['layout_view'])
        {
            case '0':
                $layout_view = $lang['All'];
                break;
            case '1':
                $layout_view = $lang['Guests'];
                break;
            case '2':
                $layout_view = $lang['Reg'];
                break;
            case '3':
                $layout_view = $lang['Owner'];
                break;
            case '4':
                $layout_view = $lang['Admins'];
                break;
        }

        if (!empty($layout_rows[$i]['groups']))
        {
            $sql = "SELECT group_name FROM " . GROUPS_TABLE . " WHERE group_id in (" . $layout_rows[$i]['groups'] . ")";
            if( !($result = $db->sql_query($sql)) )
            {
                message_die(CRITICAL_ERROR, 'Could not query user groups information', '', __LINE__, __FILE__, $sql);
            }
            $layout_groups = '';
            while ($row = $db->sql_fetchrow($result))
            {
                    $layout_groups .= '&nbsp;' . $row['group_name'] . '&nbsp;';
            }
        }
	else
        {
            $layout_groups = $lang['All'];
        }

        $template->assign_block_vars('layout', array(
            'ROW_CLASS' => $row_class,
            'NAME' => $layout_name,
			'URL' => $layout_url,
            'ID' => strval($layout_id),
            'VIEW' => $layout_view,
            'GROUPS' => $layout_groups,
            'L_DEFAULT' => ($layout_id != $default_layout) ? '<a href ="' . append_sid("admin_layout.$phpEx?default=$layout_id") . '">' . $lang['Layout_make_default'] . '</a>' : $lang['Layout_default'],
            'U_LAYOUT_EDIT' => append_sid("admin_layout.$phpEx?mode=edit&amp;layout_id=$layout_id"),
            'L_LAYOUT_DELETE' => ($layout_id != $default_layout) ? '<a href ="' . append_sid("admin_layout.$phpEx?mode=delete&amp;layout_id=$layout_id") . '">' . $lang['Delete'] . '</a>' : ''
            )
        );
    }
}

$template->pparse('body');

page_footer_admin();

?>